# -*- coding: utf-8 -*-

import pygame
import os

SCREEN_WIDTH = 480
SCREEN_HEIGHT = 800


class Base:
    SPRITES = os.path.join(
        os.path.abspath(os.path.dirname(__file__)),
        os.path.join('resources', 'image')
    )

    def __init__(self, img_paths):
        self.IMAGES = []
        self.load_images([img_paths] if type(img_paths) != list else img_paths)
        self.WIDTH, self.HEIGHT = self.IMAGES[0].get_width(), self.IMAGES[0].get_height()
        self.x, self.y = 0, 0
        self.alive = True  # 存活标志

    def load_images(self, img_paths):
        self.IMAGES = [pygame.image.load(os.path.join(Base.SPRITES, path)).convert_alpha() for path in img_paths]

    def draw(self, screen):
        screen.blit(self.IMAGES[0], (self.x, self.y))


# 玩家飞机类
class Player(Base):
    speed = 20
    DO_NOTHING = 0
    MOVE_UP, MOVE_DOWN, MOVE_LEFT, MOVE_RIGHT = list(range(1, 5))
    SHOOT = 5

    def __init__(self):
        super().__init__('hero1.png')
        self.bullets = []
        self.x, self.y = 180, 600

    def crash(self):
        self.load_images(['hero_blowup_n3.png'])
        self.alive = False

    def shoot(self):
        self.bullets.append(Bullet(self.x + self.WIDTH // 2, self.y))

    def clear_bullet(self):
        for (i, bullet) in enumerate(self.bullets):
            if bullet.y <= 0 or not bullet.alive:
                del self.bullets[i]

    def move(self, direction: int):
        assert direction in [self.MOVE_UP, self.MOVE_DOWN, self.MOVE_LEFT, self.MOVE_RIGHT]
        if direction == self.MOVE_LEFT:
            self.x = max(0, self.x - self.speed)
        elif direction == self.MOVE_RIGHT:
            self.x = min(SCREEN_WIDTH - self.WIDTH, self.x + self.speed)
        elif direction == self.MOVE_UP:
            self.y = max(0, self.y - self.speed)
        elif direction == self.MOVE_DOWN:
            self.y = min(SCREEN_HEIGHT - self.HEIGHT, self.y + self.speed)


class Bullet(Base):
    speed = 12

    def __init__(self, x, y):
        super().__init__('bullet1.png')
        self.x, self.y = x - self.WIDTH // 2, y + self.HEIGHT

    def move(self):
        self.y -= self.speed


class Enemy(Base):
    speed = 5

    def __init__(self, x=0, y=0):
        super().__init__('enemy1.png')
        self.x, self.y = x, y

    # 检测是否出界
    def check_out(self):
        return self.y >= SCREEN_HEIGHT - self.HEIGHT

    def move(self):
        self.y += self.speed

    def crash(self):
        self.load_images(['enemy1_down3.png'])
        self.alive = False
